package com.bbg.amyam.web.util.view;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.text.WordUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.format.DateTimeFormat;
import org.springframework.context.i18n.LocaleContextHolder;

import com.bbg.amyam.web.util.menu.MenuItem;

public class ControllerGenerator extends AbstractGenerator {
	private static final Log log = LogFactory.getLog(ControllerGenerator.class);
	
	private static HashMap<String,String> categoryRequestParamMappings;
	static{
		categoryRequestParamMappings=new HashMap<String,String> ();
		categoryRequestParamMappings.put("school", "/{sid:[0-9a-z]{2,20}}");
	}
	
	public ControllerGenerator(MenuItem item, boolean overwrite) {
		super(item, overwrite);
	}

	public void execute() throws IOException {
		String targetParentDir = super.getControllerDirPath();
		String controllerTemplateFile = super.getControllerTemplateFile();

		String parentTarget=this.menuItem.getTargetParent();
		parentTarget = StringUtils.replace(parentTarget,"_"," ");
		parentTarget = StringUtils.replace(parentTarget,"/"," ");
		parentTarget = WordUtils.uncapitalize(parentTarget);
		parentTarget = StringUtils.deleteWhitespace(parentTarget);
		
		String menuTarget = this.menuItem.getTarget();
		String target = StringUtils.replace(menuTarget,"_"," ");
		target = StringUtils.replaceChars(target, '/', ' ');
		target = WordUtils.capitalize(target);
		target = StringUtils.deleteWhitespace(target);

		String targetController = targetParentDir + parentTarget + File.separator
				+ target + C_MODULE_CONTROLLER_JAVA;

		
		this.replacedValues
				.put("__module__name__", parentTarget);
		this.replacedValues.put("__request_path_mapping__",
				 StringUtils.replace(menuTarget, "*", "") );
		this.replacedValues.put("__controller_name__", target);
		this.replacedValues.put("__view_name__", StringUtils.replace(menuTarget, "*", ""));
		this.replacedValues.put("__domain__name__", WordUtils.uncapitalize(this.menuItem.getDomain()));

		this.replacedValues.put("__sdomain__name__", this.menuItem.getDomain()==null?"":this.menuItem.getDomain().toLowerCase());
		this.replacedValues.put("__Cdomain__name__", WordUtils.capitalize(this.menuItem.getDomain()));
		
		this.replacedValues.put("__redirect__url__path__", "/" + StringUtils.replace(menuTarget,"*", "/\"+currentSchool.getShortName()+\""));

		log.debug("Copying  " + controllerTemplateFile + " to "
				+ targetController);

		copyFile(controllerTemplateFile, targetController);
	}

	private void copyFile(String src, String target) throws IOException {
		File targetFile = new File(target);
		if (targetFile.exists()) {
			if (!this.overwrite) {
				log.debug("Did not copy " + target + " since it exists");
				return;
			} else {
				targetFile.delete();
				log.debug("Deleted existing " + target);
			}
		}

		File srcFile = new File(src);
		List<String> lines = FileUtils.readLines(srcFile);
		ArrayList<String> newLines = new ArrayList<String>();
		boolean rmv=false;
		for (String line : lines) {
			String newLine = processLine(line);
			if(newLine.indexOf("DONT REMOVE START") > -1){
				newLines.add(newLine);
				rmv=true;
			}
			if(newLine.indexOf("DONT REMOVE END") > -1){
				rmv=false;
				newLine=updateDateFormater(newLine);
			}
			if(!rmv){
				newLines.add(newLine);
			}
		}

		FileUtils.writeLines(targetFile, newLines);
		log.debug("Copyed  " + src + " to " + target);
	}

	private String updateDateFormater(String line) {
		try {
			String domainName=this.menuItem.getDomain();
			Class<?> c = Class.forName("com.bbg.amyam.domain.model."+domainName);
			String sdomainName=WordUtils.uncapitalize(domainName);
			Field[] fields = c.getDeclaredFields();
			for(Field f:fields){
				String fname = f.getName();
				Class<?> ftype = f.getType();
				String ftypename = ftype.getName();
				if("java.util.Date".equals(ftypename)){
					String sfieldName=fname.toLowerCase();
					line = "uiModel.addAttribute(\""+sdomainName+"_"+sfieldName+"_date_format\", DateTimeFormat.patternForStyle(\"S-\", LocaleContextHolder.getLocale()));\n"+line;
				}
			}
			return line;
		} catch (ClassNotFoundException e) {
			return e.getMessage();
		}
	}
}
